package com.zyh.service;

import com.zyh.Repository.UserRepository;
import com.zyh.entity.Roles;
import com.zyh.entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService implements UserDetailsService {
    @Autowired
    UserRepository userRepository;


    @Override
    //用户登录检查
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Users users=userRepository.findByUsername(s);//根据用户名查询用户
        if (users==null){
            throw new UsernameNotFoundException("用户不存在");//如果用户不存在，抛出异常
        }
        List<GrantedAuthority> authorities=new ArrayList<>();
        List<Roles> roles=users.getRoles();
        //将用户的角色信息遍历添加进authorities中
        for (Roles role:roles){
            authorities.add(new SimpleGrantedAuthority(role.getAuthority()));
        }
        //返回用户信息（用户名，用户密码，角色）
        return new User(users.getUsername(),users.getPassword(),authorities);

    }
    //根据用户名查询用户
    public Users findByUserName(String username){
        return userRepository.findByUsername(username);
    }
    //根据角色查询用户
    public List<Users> findByRoles(Roles roles){
        return userRepository.findByRoles(roles);
    }
    //根据ID查询用户
    public Users findById(int id){
        return userRepository.findById(id);
    }
    //保存用户到数据库
    public Users save(Users users){
        return  userRepository.save(users);
    }
    //根据姓名查询用户
    public Users findByName(String info) {
        return userRepository.findByName(info);//利用jpa提供的查询接口
    }
    //根据用户名和角色查询用户
    public Users findByUsernameAndRoles(String username,Roles roles){
        return userRepository.findByUsernameAndRoles(username,roles);
    }
    //根据姓名和角色查询用户
    public Users findByNameAndRoles(String name,Roles roles){
        return userRepository.findByNameAndRoles(name,roles);
    }

}

